package com.sinopec.yelofixedreader.stock.inn.presenter

import com.sinopec.basemodule.http.CommonObserver
import com.sinopec.basemodule.http.ExceptionEngine
import com.sinopec.basemodule.model.AddPalletResultModel
import com.sinopec.yelofixedreader.stock.inn.api.StockInApi
import com.sinopec.yelofixedreader.stock.inn.contract.StockInRfidContract
import com.sinopec.yelofixedreader.stock.inn.model.StockInApiRequestModel
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

/**
 * @author lwj
 * @ClassName: StockInRfidPresenter
 * @Description: 入库-rfid扫码界面
 */
class StockInRfidPresenter(view: StockInRfidContract.View) :
    StockInRfidContract.Presenter(view) {

    /**
     * 确认入库-编码校验
     */
    override suspend fun confirmStockInOrder(model: StockInApiRequestModel): AddPalletResultModel {
        return suspendCancellableCoroutine {
            val resultObservable = StockInApi.confirmStockInOrder(model)
            toSubscribe(resultObservable,
                object : CommonObserver<AddPalletResultModel>(mView.context) {
                    override fun onNext(addPalletResultModel: AddPalletResultModel) {
                        it.resume(addPalletResultModel)
                    }

                    override fun onError(t: ExceptionEngine.ResponseThrowable) {
                        val addPalletResultModel = AddPalletResultModel()
                        addPalletResultModel.isFinishOrder = false
//                        if (model.count == 3) {
//                            addPalletResultModel.isFinishOrder = true
//                        }
                        //it.resume(addPalletResultModel)
                        it.resumeWithException(t)
                        //mView.showMessage(t.message)
                    }
                })
        }
    }

    /**
     * 确认入库完成
     */
    override fun confirmStockOutOrderFinish(outboundIntegrationId: Long) {
        val resultObservable = StockInApi.confirmStockInOrderFinish(outboundIntegrationId)
        toSubscribe(resultObservable, object : CommonObserver<Any?>(mView.context) {
            override fun onNext(s: Any) {
                mView.context.finish()
                mView.showMessage("操作成功！")
            }

            override fun onError(t: ExceptionEngine.ResponseThrowable) {
                mView.showMessage(t.message)
            }
        })
    }
}